package cqgans.app.sunao.com.cqgans.ui.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

import cqgans.app.sunao.com.cqgans.bean.Register;
import cqgans.app.sunao.com.cqgans.common.AppConstant;
import cqgans.app.sunao.com.cqgans.ui.BaseActivity;
import cqgans.app.sunao.com.cqgans.utils.FileUtils;
import cqgans.app.sunao.com.cqgansnew.R;

/**
 * Created by sunao on 2017/6/30.
 */
@ContentView(R.layout.activity_register)
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.reg_username)
    EditText reg_username;
    @ViewInject(R.id.reg_phone)
    EditText reg_phone;
    @ViewInject(R.id.reg_pwd)
    EditText reg_pwd;
    @ViewInject(R.id.reg_levelphone)
    EditText reg_levelphone;
    @ViewInject(R.id.reg_com)
    EditText reg_com;
    @ViewInject(R.id.reg_level)
    Spinner reg_level;
    @ViewInject(R.id.reg_button)
    Button reg_button;
    @ViewInject(R.id.reg_loading)
    RelativeLayout reg_loading;
    @ViewInject(R.id.reg_card)
    LinearLayout reg_card;
    @ViewInject(R.id.reg_card_img_ll)
    LinearLayout reg_card_img_ll;
    @ViewInject(R.id.reg_card_img)
    ImageView reg_card_img;
    @ViewInject(R.id.reg_camera)
    Button reg_camera;
    @ViewInject(R.id.reg_photo)
    Button reg_photo;

    @ViewInject(R.id.reg_card_side)
    LinearLayout reg_card_side;
    @ViewInject(R.id.reg_card_img_ll_side)
    LinearLayout reg_card_img_ll_side;
    @ViewInject(R.id.reg_card_img_side)
    ImageView reg_card_img_side;
    @ViewInject(R.id.reg_camera_side)
    Button reg_camera_side;
    @ViewInject(R.id.reg_photo_side)
    Button reg_photo_side;
    private String userNumber;
    private String username;
    private String mobile;
    private String levels;
    private String levelphone;
    private String password;
    private String companyName;
    private String cardImage;
    private String cardImageSide;

    private int status = 1;
    private Register register;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private boolean isSelectCardImg = false;
    private boolean isSelectCardSideImg = false;

    public static final int REQUEST_CODE_IMAGE = 10000;
    public static final int REQUEST_CODE_CAMERA = 20000;

    public static final int REQUEST_CODE_IMAGE_SIDE = 11000;
    public static final int REQUEST_CODE_CAMERA_SIDE = 21000;
    private Bitmap cardBitmap;
    private Bitmap cardSideBitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        sharedPreferences = getSharedPreferences("cqgas", Context.MODE_PRIVATE);

        initLayout();
    }

    private void initLayout() {
        reg_button.setOnClickListener(this);
        reg_camera.setOnClickListener(this);
        reg_photo.setOnClickListener(this);
        reg_camera_side.setOnClickListener(this);
        reg_photo_side.setOnClickListener(this);
        this.findViewById(R.id.back).setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        setTitleBar("用户注册", 6);
        if (isSelectCardImg) {
            reg_card_img_ll.setVisibility(View.VISIBLE);
        }
    }

    private boolean verify() {
        UUID uuid = UUID.randomUUID();

        userNumber = uuid.toString();
        username = String.valueOf(reg_username.getText());
        mobile = String.valueOf(reg_phone.getText());
        password = String.valueOf(reg_pwd.getText());
        levels = String.valueOf(reg_level.getSelectedItem());
        levelphone = String.valueOf(reg_levelphone.getText());
        password = String.valueOf(reg_pwd.getText());
        companyName = String.valueOf(reg_com.getText());
        LogUtil.i("isMobileNO(mobile)=" + isMobileNO(mobile));
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();

            return false;
        }
        if (TextUtils.isEmpty(mobile) || !isMobileNO(mobile)) {
            Toast.makeText(this, "请输入合法手机号码", Toast.LENGTH_SHORT).show();

            return false;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();


            return false;
        }
        if (TextUtils.isEmpty(levels)) {
            Toast.makeText(this, "请选择等级", Toast.LENGTH_SHORT).show();

            return false;
        }
        if (TextUtils.isEmpty(levelphone) || !isMobileNO(levelphone)) {
            Toast.makeText(this, "请输入合法上级手机号码", Toast.LENGTH_SHORT).show();


            return false;
        }

        if (TextUtils.isEmpty(companyName)) {
            Toast.makeText(this, "请输入公司", Toast.LENGTH_SHORT).show();


            return false;
        }
        if (!isSelectCardImg) {
            Toast.makeText(this, "请上传身份证正面信息", Toast.LENGTH_SHORT).show();


            return false;
        }
        if (!isSelectCardSideImg) {
            Toast.makeText(this, "请上传身份证反面信息", Toast.LENGTH_SHORT).show();


            return false;
        }
        return true;
    }

    private void register() {
        register = new Register();
        register.setUserNumber(userNumber);
        register.setUsername(username);
        register.setMobile(mobile);
        register.setLevelphone(levelphone);
        register.setLevels(levels);
        register.setPassword(password);
        register.setCompanyName(companyName);
        register.setCardImage(cardImage);
        register.setCardImageSide(cardImageSide);
        RequestParams params = new RequestParams(AppConstant.URL + AppConstant.REGISTER_URL);


        Gson gson = new Gson();

        params.setAsJsonContent(true);
        params.setBodyContent(gson.toJson(register));
        params.addHeader("Content-Type", "application/json");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(result);
                reg_loading.setVisibility(View.GONE);
                try {
                    JSONObject resultJson = new JSONObject(result);
                    if (resultJson.has("flag") && resultJson.getBoolean("flag")) {

                        Gson gson = new Gson();
//                        if (resultJson.has("data")){
//                            JSONObject data = resultJson.getJSONObject("data");
//                            JSONObject entity = data.getJSONObject("entity");
//                            User user = gson.fromJson(entity.toString(),User.class);
//                            AppConstant.user = user;
//                            if (user!=null&&user.getId()!=0){
//
//                                editor = sharedPreferences.edit();//获取编辑器
//                                editor.putString("mobile", user.getMobile());
//                                editor.putInt("id", user.getId());
//                                editor.putString("userNumber",user.getUserNumber());
//                                editor.putString("userName",user.getUsername());
//                                editor.putString("password",user.getPassword());
//                                editor.commit();
//
//                                RegisterActivity.this.startActivity(new Intent(RegisterActivity.this,HomeActivity.class));
//                                finish();
//                            }
//                        }
                        Toast.makeText(RegisterActivity.this, "注册成功，请等待审核！", Toast.LENGTH_LONG).show();
                        finish();

                    } else {
                        Toast.makeText(RegisterActivity.this, "注册失败，请检查内容后重试！", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                reg_loading.setVisibility(View.GONE);
                LogUtil.e(ex.getMessage());
                Toast.makeText(RegisterActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                reg_loading.setVisibility(View.GONE);
            }

            @Override
            public void onFinished() {

            }
        });


    }


    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.reg_button:
                if (verify()) {
                    register();
                } else {
//                    Toast.makeText(this, "请输入必填字段并检查输入内容是否正确", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.reg_camera:
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                break;

            case R.id.reg_photo:
                verifyStoragePermissions(RegisterActivity.this);

                intent = new Intent();
                if (Build.VERSION.SDK_INT < 19) {//因为Android SDK在4.4版本后图片action变化了 所以在这里先判断一下
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                } else {
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                }
                intent.setType("image/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, REQUEST_CODE_IMAGE);
                break;
            case R.id.reg_camera_side:
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CODE_CAMERA_SIDE);
                break;

            case R.id.reg_photo_side:
                verifyStoragePermissions(RegisterActivity.this);

                intent = new Intent();
                if (Build.VERSION.SDK_INT < 19) {//因为Android SDK在4.4版本后图片action变化了 所以在这里先判断一下
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                } else {
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                }
                intent.setType("image/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, REQUEST_CODE_IMAGE_SIDE);
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    private void updateImg() {
        isSelectCardImg = true;
        cardImage = bitmapToBase64(cardBitmap);
        reg_card_img_ll.setVisibility(View.VISIBLE);
        reg_card_img.setImageBitmap(cardBitmap);
    }

    private void updateSideImg() {
        isSelectCardSideImg = true;
        cardImageSide = bitmapToBase64(cardSideBitmap);
        reg_card_img_ll_side.setVisibility(View.VISIBLE);
        reg_card_img_side.setImageBitmap(cardSideBitmap);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][35678]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null) {
                this.finish();
                return;
            }
            Uri uri = data.getData();
            switch (requestCode) {
                case REQUEST_CODE_IMAGE:
                    String path = FileUtils.getUriPath(this, uri); //（因为4.4以后图片uri发生了变化）通过文件工具类 对uri进行解析得到图片路径
                    cardBitmap = BitmapFactory.decodeFile(path);
                    cardBitmap = ratio(cardBitmap, 640, 480);
                    updateImg();
                    break;

                case REQUEST_CODE_CAMERA:
                    Bundle bundle = data.getExtras();
                    // 获取相机返回的数据，并转换为Bitmap图片格式，这是缩略图
                    cardBitmap = (Bitmap) bundle.get("data");
                    cardBitmap = ratio(cardBitmap, 640, 480);
                    updateImg();

                    break;


                    case REQUEST_CODE_IMAGE_SIDE:
                        String pathside = FileUtils.getUriPath(this, uri); //（因为4.4以后图片uri发生了变化）通过文件工具类 对uri进行解析得到图片路径
                        cardSideBitmap = BitmapFactory.decodeFile(pathside);
                        cardSideBitmap = ratio(cardSideBitmap, 640, 480);
                        updateSideImg();
                        break;

                    case REQUEST_CODE_CAMERA_SIDE:
                        Bundle bundleside = data.getExtras();
                        // 获取相机返回的数据，并转换为Bitmap图片格式，这是缩略图
                        cardSideBitmap = (Bitmap) bundleside.get("data");
                        cardSideBitmap = ratio(cardSideBitmap, 640, 480);
                        updateSideImg();

                        break;
                    default:
                        break;
                }



        }

    }


    public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        //压缩好比例大小后再进行质量压缩
//      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
        return bitmap;
    }

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};


    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
